<template>
  <div class="mod-send-address">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>寄件地址管理</span>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">
            <el-icon><Edit /></el-icon>
            编辑地址
          </el-button>
          <div v-else>
            <el-button type="primary" @click="handleSave" :loading="saveLoading">
              <el-icon><Check /></el-icon>
              保存
            </el-button>
            <el-button @click="handleCancel">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 查看模式 -->
        <el-form
          v-if="!isEditing"
          label-width="120px"
          class="view-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收件人：">
                <span class="form-value">{{ addressData.receiver }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话：">
                <span class="form-value">{{ addressData.mobile }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址：">
                <span class="form-value">{{ addressData.addr }}</span>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>

        <!-- 编辑模式 -->
        <el-form
          v-else
          ref="addressFormRef"
          :model="editForm"
          :rules="formRules"
          label-width="120px"
          class="edit-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收件人" prop="receiver">
                <el-input
                  v-model="editForm.receiver"
                  placeholder="请输入收件人姓名"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="mobile">
                <el-input
                  v-model="editForm.mobile"
                  placeholder="请输入联系电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="所在地区" prop="areaCode">
                <el-cascader
                  v-model="editForm.areaCode"
                  :options="areaOptions"
                  :props="cascaderProps"
                  placeholder="请选择所在地区"
                  style="width: 100%"
                  @change="handleAreaChange"
                />
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="addr">
                <el-input
                  v-model="editForm.addr"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入详细地址"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const loading = ref(false)
const isEditing = ref(false)
const saveLoading = ref(false)
const addressFormRef = ref()

// 地址数据
const addressData = ref({
  addrId: '',
  receiver: '',
  province: '',
  city: '',
  area: '',
  addr: '',
  mobile: '',
  commonAddr: 0,
  provinceId: '',
  cityId: '',
  areaId: ''
})

// 编辑表单
const editForm = reactive({
  addrId: '',
  receiver: '',
  addr: '',
  mobile: '',
  areaCode: [],
  provinceId: '',
  cityId: '',
  areaId: ''
})

// 表单验证规则
const formRules = {
  receiver: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  areaCode: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  addr: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 200, message: '详细地址长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 地区选项（模拟数据，实际项目中应该从后端获取）
const areaOptions = ref([
  {
    value: '320000000000',
    label: '江苏省',
    children: [
      {
        value: '320900000000',
        label: '盐城市',
        children: [
          {
            value: '320903000000',
            label: '盐都区'
          }
        ]
      }
    ]
  }
])

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

// 获取寄件地址信息
const getAddressInfo = async () => {
  loading.value = true
  try {
    const response = await http({
      url: import.meta.env.VITE_APP_USER_API + '/p/address/addrInfo/getReceiveAddr',
      method: 'get',
      params: http.adornParams()
    })
    console.log(response)
    if (response.code === '00000' && response.data) {
      addressData.value = response.data
      // 设置编辑表单的初始值
      Object.assign(editForm, {
        addrId: response.data.addrId,
        receiver: response.data.receiver,
        mobile: response.data.mobile,
        addr: response.data.addr,
        areaCode: [response.data.provinceId, response.data.cityId, response.data.areaId],
        provinceId: response.data.provinceId,
        cityId: response.data.cityId,
        areaId: response.data.areaId
      })
    } else {
      ElMessage.error(response.msg || '获取地址信息失败')
    }
  } catch (error) {
    // ElMessage.error('获取地址信息失败')
  } finally {
    loading.value = false
  }
}

// 处理地区变更
const handleAreaChange = (value) => {
  if (value && value.length === 3) {
    editForm.provinceId = value[0]
    editForm.cityId = value[1]
    editForm.areaId = value[2]
  }
}

// 编辑地址
const handleEdit = () => {
  isEditing.value = true
}

// 保存地址
const handleSave = async () => {
  // 表单验证
  await addressFormRef.value.validate()

  saveLoading.value = true
  try {
    const response = await http({
      url: import.meta.env.VITE_APP_USER_API + '/p/address/updateReceiveAddr',
      method: 'post',
      data: http.adornData({
        addrId: editForm.addrId,
        receiver: editForm.receiver,
        addr: editForm.addr,
        mobile: editForm.mobile
      })
    })

    if (response.code === '00000') {
      ElMessage.success('地址更新成功')
      isEditing.value = false
      // 重新获取地址信息
      await getAddressInfo()
    } else {
      ElMessage.error(response.msg || '地址更新失败')
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败不会弹出错误
      ElMessage.error('地址更新失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 取消编辑
const handleCancel = () => {
  isEditing.value = false
  // 重置表单
  addressFormRef.value?.resetFields()
  // 恢复原始数据
  Object.assign(editForm, {
    addrId: addressData.value.addrId,
    receiver: addressData.value.receiver,
    mobile: addressData.value.mobile,
    addr: addressData.value.addr,
    areaCode: [addressData.value.provinceId, addressData.value.cityId, addressData.value.areaId],
    provinceId: addressData.value.provinceId,
    cityId: addressData.value.cityId,
    areaId: addressData.value.areaId
  })
}

// 页面加载时获取地址信息
onMounted(() => {
  getAddressInfo()
})
</script>

<style lang="scss" scoped>
.mod-send-address {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .form-value {
    color: #303133;
    font-weight: 500;
  }

  .view-form {
    padding: 20px 0;
  }

  .edit-form {
    padding: 20px 0;
  }

  :deep(.el-card__header) {
    background-color: #f5f7fa;
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}
</style>
